/**
 * 在实验室中进行数据更新与分析的例程，用于说明多线程并发问题
 * */
package thread;

public class J_Synchronization {
    public static void main(String args[]){
        J_Experiment data = new J_Experiment();
        J_Assistant threadA = new J_Assistant(data);
        J_Analyst threadB = new J_Analyst(data);
        threadA.start();;
        threadB.start();
    }
}

/**
 * 实验
 * */
class J_Experiment{
    //温度和气压
    private int m_temperature,m_pressure;
    public void mb_update(int t,int p){
        m_temperature = t;
        m_pressure= p;
    }

    //数据分析
    public void mb_analyze() {
        int t = m_temperature;
        int p =m_pressure;
        //进行延时，使得并发问题更容易出现
        for (int i = 0; i < 1000; i++) {

        }
        if (t!= m_temperature){
            System.out.print("温度实验数据出现情况：");
            System.out.printf("t(%1$d)!=(%2$d)\r\n",t,m_temperature);
            System.exit(0);
        }
        if (p!= m_pressure){
            System.out.print("气压实验数据出现情况：");
            System.out.printf("t(%1$d)!=(%2$d)\r\n",p,m_pressure);
            System.exit(0);
        }
    }
}

/**
 * 实验室的助理人员
 * */
class J_Assistant extends Thread{
    J_Experiment m_data;
    public J_Assistant(J_Experiment d){
        m_data = d;
    }

    @Override
    public void run() {
        int i,j;
        while (true){
            i = (int)(Math.random()*1000);
            j = (int)(Math.random()*1000);
            m_data.mb_update(i,j);
        }
    }
}

class J_Analyst extends Thread{
    J_Experiment m_data;
    public J_Analyst(J_Experiment d){
        m_data = d;
    }

    @Override
    public void run() {
        while (true){
            m_data.mb_analyze();
        }
    }
}